<?php

require_once("../db/db.php");
	
class Tags {
		
	public function __construct() {	
	}
	
	public function getAllTags() {
		$db = new Database();
		
		$result = $db->executeQuery("SELECT * FROM tag");
		$result = $db->parseIntegers($result, "id");
		
		return $result;
	}
	
	public function getTagIds($tags) {
		$db = new Database();
		
		$result = array();
		foreach($tags as $tag) {
			$query = "SELECT id FROM tag WHERE ";
			$parts = explode("=",$tag);
			
			if (count($parts) == 2) {
				$query = $query . "name='" . $parts[0] . "' AND parameter='" . $parts[1] . "';";
			}
			else {
				$query = $query . "name='" . $tag . "';";
			}
			$data = $db->executeQuery($query);
			if (count($data)  > 0) {
			$bla = $db->parseIntegers($data, "id");
				$result[] = $bla[0]["id"];
			}
		}
		
		return $result;
	}
	
	public function saveTags($tags) {
		$db = new Database();
				
		foreach($tags as $tag) {
			$parts = explode("=", $tag);
			$doesNotExist = true;
			if (count($parts) == 2) {
				$result = $db->executeQuery("SELECT * FROM tag WHERE name='" . $parts[0] . "' AND parametar='" . $parts[1] . "';");
				$doesNotExist = count($result) == 0;
			}
			else {
				$result = $db->executeQuery("SELECT * FROM tag WHERE name='" . $tag . "';");
				$doesNotExist = count($result) == 0;
			}
			
			$tagId = $db->getMax("tag", "id", true) + 1;
			
			if ($doesNotExist) {
				if (count($parts) == 2) {
					$db->executeQuery("INSERT INTO tag(id, name, parametar) VALUES('" . $tagId . "', '" . $parts[0] . "', '" . $parts[1] . "');");
				}
				else {
					$db->executeQuery("INSERT INTO tag(id, name) VALUES('" . $tagId . "', '" . $tag . "');");
				}
			}
		}
	}
	
	public function __destruct() {
	}
}
?>